# cpu信息
from lib.config.settings import settings
import os
class Cpu:
    def process(self, func_name):
        if not settings.DEBUG:  # 测试环境
            BASE_DIR = settings.BASE_DIR
            path = os.path.join(BASE_DIR, r'files\cpuinfo.out')
            fp = open(r'%s' % path, 'r', encoding='utf-8')
            info = fp.read()
            return self.parse(info)

        content = func_name('cat /proc/cpuinfo')   # 执行采集信息的命令
        return self.parse(content)

    def parse(self, content):
              # cpu的总(逻辑，物理)个数    physical_id 物理表示 物理cpu的个数       cpu的型号
        response = {'cpu_count': 0,            'cpu_physical_count': 0,          'cpu_model': ''}
        cpu_physical_set = set()
        line = content.split('\n\n')  # 多核以空行切割
        for lin in line:
            key = lin.split('\n')
            for data in key:
                if len(data.split(':')) == 2:
                    key1, value = data.split(':')
                    key1 = key1.strip('\t')
                    if key1 == 'processor':  # 逻辑处理器
                        response['cpu_count'] += 1
                    elif key1 == 'model name':  # cpu型号
                        if not response['cpu_model']:
                            response['cpu_model'] = value
                    elif key1 == 'physical id':  # 物理处理器的id
                        cpu_physical_set.add(value)
        response['cpu_physical_count'] = len(cpu_physical_set)
        return response




